package com.zhiwei.fast.fragments.models

import com.blankj.utilcode.util.GsonUtils
import com.zhiwei.most.base.viewmodel.BaseViewModel
import com.zhiwei.most.ext.klog
import no.nordicsemi.android.support.v18.scanner.*

/**
 * Create by zhiweizhu on 2022/3/3
 */
class BleScantViewModel: BaseViewModel() {

    private val mBleScanCallback: BleScanCallback by lazy(LazyThreadSafetyMode.NONE){
        BleScanCallback()
    }
    
    private var mScantStatus: Boolean = false
    
    private val mBluetoothLeScannerCompat : BluetoothLeScannerCompat by lazy(LazyThreadSafetyMode.NONE){
        BluetoothLeScannerCompat.getScanner()
    }


    /**
     * 开始扫描
     */
    fun startScant(filters : List<ScanFilter>? = null){
        if(mScantStatus){
            klog("startScant: 蓝牙扫描中")
            return
        }
        mScantStatus = true
        mBluetoothLeScannerCompat.startScan(
            filters,
            ScanSettings.Builder()
                .setLegacy(false)
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .setReportDelay(0)   //大于0 onScanResult方法不会回调
                .setUseHardwareBatchingIfSupported(false)
                .build(),
            mBleScanCallback
        )
    }

    /**
     * 判断是否扫描中
     * @return true 表示扫描中 false 表示未开始扫描或者停止扫描
     */
    fun isScant(): Boolean = mScantStatus

    /**
     * 停止扫描
     */
    fun stopScant(){
        if(!mScantStatus){
            klog("stopScant: 蓝牙没有开始扫描，不用进行停止")
            return
        }
        mScantStatus = false
        mBluetoothLeScannerCompat.stopScan(mBleScanCallback)
    }



    inner class BleScanCallback : ScanCallback(){
        
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            klog("onScanResult: 回调类型：$callbackType, 数据：名称->${result.scanRecord?.deviceName},${result.device.name}")


        }

        override fun onBatchScanResults(results: MutableList<ScanResult>) {
            super.onBatchScanResults(results)
            klog("onBatchScanResults: 数据：${GsonUtils.toJson(results)}")
        }

        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            klog("onScanFailed: 扫描失败< 错误码：$errorCode")
        }
    }






}